
/*
 File: RootViewController.m
 Abstract: View controller to manage a scrollview that displays a zoomable image.
 
 Version: 1.1
 
 Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple
 Inc. ("Apple") in consideration of your agreement to the following
 terms, and your use, installation, modification or redistribution of
 this Apple software constitutes acceptance of these terms.  If you do
 not agree with these terms, please do not use, install, modify or
 redistribute this Apple software.
 
 In consideration of your agreement to abide by the following terms, and
 subject to these terms, Apple grants you a personal, non-exclusive
 license, under Apple's copyrights in this original Apple software (the
 "Apple Software"), to use, reproduce, modify and redistribute the Apple
 Software, with or without modifications, in source and/or binary forms;
 provided that if you redistribute the Apple Software in its entirety and
 without modifications, you must retain this notice and the following
 text and disclaimers in all such redistributions of the Apple Software.
 Neither the name, trademarks, service marks or logos of Apple Inc. may
 be used to endorse or promote products derived from the Apple Software
 without specific prior written permission from Apple.  Except as
 expressly stated in this notice, no other rights or licenses, express or
 implied, are granted by Apple herein, including but not limited to any
 patent rights that may be infringed by your derivative works or by other
 works in which the Apple Software may be incorporated.
 
 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
 MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
 THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
 FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
 OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
 MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
 AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
 STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 
 Copyright (C) 2010 Apple Inc. All Rights Reserved.
 
 */

#import "RootViewController.h"


#define ZOOM_VIEW_TAG 100
#define ZOOM_STEP 0.25

#define THUMB_HEIGHT 150
#define THUMB_V_PADDING 10
#define THUMB_H_PADDING 10
#define CREDIT_LABEL_HEIGHT 20

#define AUTOSCROLL_THRESHOLD 30

@interface RootViewController (ViewHandlingMethods)
- (void)toggleThumbView;
- (void)pickImageNamed:(NSString *)name;
- (NSArray *)imageNames;
- (void)createThumbScrollViewIfNecessary;
- (void)createSlideUpViewIfNecessary;
@end

@interface RootViewController (AutoscrollingMethods)
//- (void)maybeAutoscrollForThumb:(ThumbImageView *)thumb;
- (void)autoscrollTimerFired:(NSTimer *)timer;
- (void)legalizeAutoscrollDistance;
- (float)autoscrollDistanceForProximityToEdge:(float)proximity;
@end

@interface RootViewController (UtilityMethods)
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center;
@end



@implementation RootViewController
@synthesize btnFindMe;
@synthesize lblLatLong;
@synthesize location;
@synthesize theMap;

- (void)loadView {
    [super loadView];
   
	
    imageScrollView = [[UIScrollView alloc] initWithFrame:[[self view] bounds]];
    [imageScrollView setBackgroundColor:[UIColor blackColor]];
    [imageScrollView setDelegate:self];
    [imageScrollView setBouncesZoom:YES];
    [[self view] addSubview:imageScrollView];
    [[self view] sendSubviewToBack:imageScrollView];

	drawOnMapView = [[DrawOnMap alloc] initWithFrame:[[self view] bounds]];
	NSLog(@"DrawonMApViewFrame ox:%lf, oy%lf, w:%lf, h%lf",[drawOnMapView frame].origin.x,[drawOnMapView frame].origin.y,[drawOnMapView frame].size.width,[drawOnMapView frame].size.height);

    

	[self startStandardUpdates ];// start location manager
	location=locationManager.location; 
	
	track=[[NSMutableArray alloc] init];
	
	theMap=[[Map alloc] init];
	
	[self pickImageNamed:theMap.file];
	
}

- (void)dealloc {
    [imageScrollView release];
	[location release];
	[theMap release];
    //[slideUpView release];
    //[thumbScrollView release];
    [super dealloc];
}

#pragma mark UIScrollViewDelegate methods

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    UIView *view = nil;
    if (scrollView == imageScrollView) {
        view = [imageScrollView viewWithTag:ZOOM_VIEW_TAG];
    }
    return view;
}

/************************************** NOTE **************************************/
/* The following delegate method works around a known bug in zoomToRect:animated: */
/* In the next release after 3.0 this workaround will no longer be necessary      */
/**********************************************************************************/
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale {
   // [scrollView setZoomScale:scale+0.01 animated:NO];
    //[scrollView setZoomScale:scale animated:NO];
	//drawOnMapView.transform = CGAffineTransformMakeScale(1/scale,1/scale);

}

#pragma mark TapDetectingImageViewDelegate methods

 - (void)tapDetectingImageView:(TapDetectingImageView *)view gotSingleTapAtPoint:(CGPoint)tapPoint {
	//// Single tap shows or hides drawer of thumbnails.
	//[self toggleThumbView];
}

- (void)tapDetectingImageView:(TapDetectingImageView *)view gotDoubleTapAtPoint:(CGPoint)tapPoint {
	// double tap zooms in
	float newScale = [imageScrollView zoomScale]*ZOOM_STEP;
	CGRect zoomRect = [self zoomRectForScale:newScale withCenter:tapPoint];
	//[imageScrollView zoomToRect:zoomRect animated:YES];
}

- (void)tapDetectingImageView:(TapDetectingImageView *)view gotTwoFingerTapAtPoint:(CGPoint)tapPoint {
	// two-finger tap zooms out
	float newScale = [imageScrollView zoomScale] / ZOOM_STEP;
	CGRect zoomRect = [self zoomRectForScale:newScale withCenter:tapPoint];
	//[imageScrollView zoomToRect:zoomRect animated:YES];
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
//	drawOnMapView.frame=[[imageScrollView viewWithTag:ZOOM_VIEW_TAG] frame];
//	drawOnMapView.transform = CGAffineTransformMakeScale([imageScrollView zoomScale], [imageScrollView zoomScale]);

}



- (void)pickImageNamed:(NSString *)name {
	
	NSLog(@"pickImage");
	// first remove previous image view, if any
	[[imageScrollView viewWithTag:ZOOM_VIEW_TAG] removeFromSuperview];
	
	UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.png", name]];
	TapDetectingImageView *zoomView = [[TapDetectingImageView alloc] initWithImage:image];
	[zoomView setDelegate:self];
	[zoomView setTag:ZOOM_VIEW_TAG];
	[zoomView addSubview:drawOnMapView];
	zoomView.autoresizesSubviews=NO;
	
	
//	[imageScrollView addSubview:drawOnMapView];
//	[imageScrollView sendSubviewToBack:drawOnMapView];
//	[imageScrollView setContentSize:[drawOnMapView frame].size];
//	
	[imageScrollView addSubview:zoomView];
	[imageScrollView sendSubviewToBack:zoomView];
	[imageScrollView setContentSize:[zoomView frame].size];
	
	

	drawOnMapView.frame=[zoomView frame];
	drawOnMapView.contentMode=UIViewContentModeTopLeft;	


	//NSLog(@" imagescrollview content size = %f %f",[imageScrollView contentSize].width, [imageScrollView contentSize].height);	
	//NSLog(@" Image scrollview size = %f %f",[imageScrollView frame].size.width, [imageScrollView frame].size.height);
	//NSLog(@" imagescrollview content size = %f %f",[imageScrollView contentSize].width, [imageScrollView contentSize].height);
	
	
	// choose minimum scale so image width fits screen
	float minScale  = [imageScrollView frame].size.height  / [zoomView frame].size.height;

	[imageScrollView setMinimumZoomScale:minScale];
	[imageScrollView setMaximumZoomScale:10];

	[imageScrollView setZoomScale:1];
	
	//NSLog(@" imagescrollview content size = %f %f",[imageScrollView contentSize].width, [imageScrollView contentSize].height);

	[imageScrollView setContentOffset:CGPointZero];
	
	//NSLog(@" Image scrollview size = %f %f",[imageScrollView frame].size.width, [imageScrollView frame].size.height);
	//NSLog(@" imagescrollview content size = %f %f",[imageScrollView contentSize].width, [imageScrollView contentSize].height);
	
	//NSLog(@" Drawmapview frame size = %f %f",[drawOnMapView frame].size.width, [drawOnMapView frame].size.height);

	
	NSLog(@"DrawonMApViewFrame ox:%lf, oy%lf, w:%lf, h%lf",[drawOnMapView frame].origin.x,[drawOnMapView frame].origin.y,[drawOnMapView frame].size.width,[drawOnMapView frame].size.height);

	[zoomView release];
}



#pragma mark Utility methods

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center {
	NSLog(@"ZoomRectforScale");
    
    CGRect zoomRect;
    
    // the zoom rect is in the content view's coordinates. 
    //    At a zoom scale of 1.0, it would be the size of the imageScrollView's bounds.
    //    As the zoom scale decreases, so more content is visible, the size of the rect grows.
    zoomRect.size.height = [imageScrollView frame].size.height / scale;
    zoomRect.size.width  = [imageScrollView frame].size.width  / scale;


    
    // choose an origin so as to get the right center.
    zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);
    
	NSLog(@" zoomRect size = %f %f",zoomRect.size.width,zoomRect.size.height);
	NSLog(@" zoomRect org  = %f %f",zoomRect.origin.x,zoomRect.origin.y  );
	NSLog(@" zoomRect centre  = %f %f",zoomRect.origin.x+zoomRect.size.width/2,zoomRect.origin.y+zoomRect.size.height/2  );

	
    return zoomRect;
}



-(IBAction)buttonPress:(id)sender{
	
	NSLog(@"ButtonPress");
	
	#if TARGET_IPHONE_SIMULATOR
	[self getFakeLocation]; //generate fake location if on simulator
	#endif
	TapDetectingImageView *zoomView=(TapDetectingImageView*)[imageScrollView viewWithTag:ZOOM_VIEW_TAG];

	
	CGPoint pixOnMap=[theMap GetPixelCoordsOnMap:[drawOnMapView frame]:location];


	//NSString* str=[NSString stringWithFormat:@"Lat:%lf Long%lf",lat,lng];
	NSString* str=[NSString stringWithFormat:@"x:%lf y%lf",location.coordinate.longitude,location.coordinate.latitude];
	
	lblLatLong.text=str;
	
	
	NSLog(@" pixx:%lf pixy%lf",pixOnMap.x,pixOnMap.y);
	
	CGRect zoomRect = [self zoomRectForScale:[imageScrollView zoomScale] withCenter:pixOnMap];
	[imageScrollView zoomToRect:zoomRect animated:YES];
	
	//drawOnMapView.rect1=zoomRect;
	
	//NSLog(@" zoomView size = %f %f",[zoomView frame].size.width, [zoomView frame].size.height);
	NSLog(@"Zoom Frame \tox:%lf, \toy%lf, \tw:%lf, \th%lf",[zoomView frame].origin.x,[zoomView frame].origin.y,[zoomView frame].size.width,[zoomView frame].size.height);
	CGAffineTransform  t=zoomView.transform ;
	NSLog(@"zoomTransform %f %f",t.a,t.b);
	NSLog(@"zoomTransformTransform %f %f",t.c,t.d);
	NSLog(@"zoomTransformTransform %f %f",t.tx,t.ty);
	
	NSLog(@"Self Frame \tox:%lf, \toy%lf, \tw:%lf, \th%lf",[[self view] frame].origin.x,[[self view] frame].origin.y,[[self view] frame].size.width,[[self view] frame].size.height);
	NSLog(@"Img Frame\tox:%lf, \toy%lf, \tw:%lf, \th%lf",[imageScrollView frame].origin.x,[imageScrollView frame].origin.y,[imageScrollView frame].size.width,[imageScrollView frame].size.height);
	NSLog(@"DrawMap Frame \tox:%lf, \toy%lf, \tw:%lf, \th%lf",[drawOnMapView frame].origin.x,[drawOnMapView frame].origin.y,[drawOnMapView frame].size.width,[drawOnMapView frame].size.height);
	//NSLog(@" Drawonmapview content size = %f %f",[drawOnMapView	contentSize].width, [drawOnMapView contentSize].height);

	//drawOnMapView.lng=(r2/LONG_MAX)*imageScrollView.contentSize.width;
	//drawOnMapView.lat=(r1/LONG_MAX)*imageScrollView.contentSize.height;
	
	drawOnMapView.markerLocation=location;
	//NSLog(@" pixx:%lf pixy%lf",drawOnMapView.lnglat.x,drawOnMapView.lnglat.y);
	
//	CGRect zoomRect2;
    
    // the zoom rect is in the content view's coordinates. 
    //    At a zoom scale of 1.0, it would be the size of the imageScrollView's bounds.
    //    As the zoom scale decreases, so more content is visible, the size of the rect grows.
//    zoomRect2.size.height = [imageScrollView frame].size.height / [imageScrollView zoomScale];
//    zoomRect2.size.width  = [imageScrollView frame].size.width  / [imageScrollView zoomScale];
//	drawOnMapView.lng=zoomRect2.size.width/2;
//	drawOnMapView.lat=zoomRect2.size.height/2;
	
	[self updateTrackOnMap];
	
		
}

- (void)startStandardUpdates// start location tracking
{
    // Create the location manager if this object does not
    // already have one.
    if (nil == locationManager)
        locationManager = [[CLLocationManager alloc] init];
	
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	
    // Set a movement threshold for new events.
    locationManager.distanceFilter = kCLDistanceFilterNone;
	
    [locationManager startUpdatingLocation];
}

// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation
{
	
	// If it's a relatively recent event, turn off updates to save power
    //NSDate* eventDate = newLocation.timestamp;
    ////NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
    //if (abs(howRecent) < 15.0)
    //{
	
	location=newLocation;
	[location retain];
	[track addObject:location];
	
	//update map
	[self updateTrackOnMap];
	
	//}
    // else skip the event and process the next one.

	NSLog(@"latitude %+.6f, longitude %+.6f\n",
		  location.coordinate.latitude,
		  location.coordinate.longitude);
}

-(void)getFakeLocation{//for the simulator
//	double r1=random();
//	double r2=random();
//	
//	double lat=theMap.mapFrame.origin.y+(r1/LONG_MAX)*theMap.mapFrame.size.height;
//	double lng=theMap.mapFrame.origin.x+(r2/LONG_MAX)*theMap.mapFrame.size.width;
//	
//	CLLocation *l=[[CLLocation alloc]initWithLatitude:lat longitude:lng];
//	location=l;
//	[track addObject:location];
//		
//	[self updateTrackOnMap];
//
//	[l release];
	
	const int numPlaces =5;
	double places[5][2]={
		{52.74404736066856,-6.773500442504883}, //my house
		{52.747333700266125,-6.781611442565918},// ballykealy text
		{52.735005,-6.792383},// sw corner
		{52.73891601870526,-6.761269569396973}, //field
		{52.74148826057621,-6.771955490112305}, //	texaco
	};
	
	double r1=random();
	
	int idx=((long)r1)%numPlaces;
	
	CLLocation *l=[[CLLocation alloc]initWithLatitude:places[idx][0] longitude:places[idx][1]];
	location=l;
	
	NSLog(@"latitude %+.6f, longitude %+.6f\n",
		  location.coordinate.latitude,
		  location.coordinate.longitude);
	
	[track addObject:location];
			
	[self updateTrackOnMap];
	
	[l release];
	
		
		
}	

-(void)updateTrackOnMap{
	drawOnMapView.track=track;
	drawOnMapView.map=theMap;
	[drawOnMapView setNeedsDisplay];
	
}


//- (NSArray *)imageNames {
//	
//	// the filenames are stored in a plist in the app bundle, so create array by reading this plist
//	NSString *path = [[NSBundle mainBundle] pathForResource:@"Images" ofType:@"plist"];
//	NSData *plistData = [NSData dataWithContentsOfFile:path];
//	NSString *error; NSPropertyListFormat format;
//	NSArray *imageNames = [NSPropertyListSerialization propertyListFromData:plistData
//														   mutabilityOption:NSPropertyListImmutable
//																	 format:&format
//														   errorDescription:&error];
//	if (!imageNames) {
//		NSLog(@"Failed to read image names. Error: %@", error);
//		[error release];
//	}
//	
//	return imageNames;
//}
@end
